package cn.opencodes.framework.autoconfigure;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.web.filter.DelegatingFilterProxy;

import cn.opencodes.framework.autoconfigure.properties.AlphaProperties;
import cn.opencodes.framework.core.shiro.AuthcRealm;
import cn.opencodes.framework.core.shiro.AuthcSecretFilter;
import cn.opencodes.framework.core.shiro.AuthcTokenFilter;

/**
 * Shiro配置
 * @author HJ
 */
public class ShiroConfiguration {

    @Bean
    public FilterRegistrationBean<DelegatingFilterProxy> shiroFilterRegistration() {
        FilterRegistrationBean<DelegatingFilterProxy> registration = new FilterRegistrationBean<>();
        registration.setFilter(new DelegatingFilterProxy("shiroFilter"));
        //该值缺省为false，表示生命周期由SpringApplicationContext管理，设置为true则表示由ServletContainer管理
        registration.addInitParameter("targetFilterLifecycle", "true");
        registration.setEnabled(true);
        registration.setOrder(Integer.MAX_VALUE - 1);
        registration.addUrlPatterns("/*");
        return registration;
    }

    @Bean("sessionManager")
    public SessionManager sessionManager(){
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        sessionManager.setSessionValidationSchedulerEnabled(true);
        sessionManager.setSessionIdCookieEnabled(true);
        return sessionManager;
    }

    @Bean("securityManager")
    public SecurityManager securityManager(SessionManager sessionManager) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(new AuthcRealm());
        securityManager.setSessionManager(sessionManager);
        return securityManager;
    }
    
    
    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shirFilter(
	    		SecurityManager securityManager, AlphaProperties props) {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(securityManager);
        shiroFilter.setLoginUrl("/"+props.getModule()+props.getLoginUrl());
        shiroFilter.setSuccessUrl("/index.html");
        //****************swagger****************************//
        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/swagger-ui.html", "anon");
        filterMap.put("/webjars/springfox-swagger-ui/**", "anon");
        filterMap.put("/swagger-resources/**", "anon");
        filterMap.put("/v2/api-docs", "anon");
        //****************系统应用****************************//
        filterMap.put("/"+props.getModule()+"/druid/**", "anon");
        //****************动态加载配置文件的filterMap***************//
        List<String> filterList = props.getFilters();
        if (filterList != null) {
        	for (String filter : filterList) {
        		String[] fs = filter.split(":");
        		if (fs[1].indexOf("myAuthcSecret")!=-1 && !props.isOpenSecret()) {
					continue;
				}
        		filterMap.put(fs[0].trim(), fs[1].trim());
        	}
		}
        //****************oauth过滤****************************//
        Map<String, Filter> filters = new HashMap<>();
        if ( props.isOpenSecret() ) {
        	filters.put("myAuthcSecret", new AuthcSecretFilter());
        	filterMap.put("/"+props.getModule()+props.getLoginUrl(), "myAuthcSecret");
		}
        if ( props.isOpenToken() ) {
			filters.put("myAuthcToken", new AuthcTokenFilter(props));
        	filterMap.put("/"+props.getModule()+"/**", "myAuthcToken");
        }
        shiroFilter.setFilters(filters);
        shiroFilter.setFilterChainDefinitionMap(filterMap);
        return shiroFilter;
    }

    @Bean("lifecycleBeanPostProcessor")
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    @Bean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator proxyCreator = new DefaultAdvisorAutoProxyCreator();
        proxyCreator.setProxyTargetClass(true);
        return proxyCreator;
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }

}
